//
//  UITabBarController+Add.m
//  MuMu
//
//  Created by 刘川 on 2017/7/13.
//  Copyright © 2018年 com.Alex All rights reserved.
//

#import "UITabBarController+Add.h"

@implementation UITabBarController (Add)

#define TabbarItemNums 3.0    //tabbar的数量

- (void)showBadgeOnItemIndex:(NSInteger)index{
    
    [self removeBadgeOnItemIndex:index];
    UIImageView * badgeImageView = [[UIImageView alloc]init];
    badgeImageView.image = [UIImage imageNamed:@"message_redbage"];
    badgeImageView.tag =888 + index;
    CGRect tabFrame = self.tabBar.frame;
    float percentX = (index +0.6) /TabbarItemNums;
    CGFloat x = ceilf(percentX * tabFrame.size.width);
    CGFloat y = ceilf(0.1 * tabFrame.size.height);
    badgeImageView.frame =CGRectMake(x+1, y+3, 8,8);
    [self.tabBar addSubview:badgeImageView];
}

- (void)hideBadgeOnItemIndex:(NSInteger)index{
    [self removeBadgeOnItemIndex:index];
}

- (void)removeBadgeOnItemIndex:(NSInteger)index{
    for (UIView *subView in self.tabBar.subviews) {
        if (subView.tag == 888+index) {
            [subView removeFromSuperview];
        }
    }
}

- (void)addChildViewControllerName:(NSString *) childVcName
                             title:(NSString *) title
                        titleColor:(UIColor *) titleColor
                     selectedColor:(UIColor *) selectedColor
                             image:(NSString *) image
                     selectedImage:(NSString *) selectedImage
                       imageInsets:(UIEdgeInsets) imageInsets
                     titlePosition:(UIOffset) titlePosition
                 navControllerName:(NSString *) navControllerName; {
    
    Class class = NSClassFromString(childVcName);
    if (class) {
        UIViewController *childVc = [class new];
        childVc.title = title;
        childVc.tabBarItem.image = [UIImage imageNamed:image];
        childVc.tabBarItem.selectedImage = [[UIImage imageNamed:selectedImage]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        childVc.tabBarItem.imageInsets = imageInsets;
        childVc.tabBarItem.titlePositionAdjustment = titlePosition;

        [[UITabBarItem appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:titleColor,NSForegroundColorAttributeName,nil] forState:UIControlStateNormal];
        [[UITabBarItem appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:selectedColor, NSForegroundColorAttributeName,nil] forState:UIControlStateSelected];
        
        id nav = nil;
        Class navClass = NSClassFromString(navControllerName);
        if (navClass) {
            nav = [[navClass alloc] initWithRootViewController:childVc];
        }else{
            nav = [[UINavigationController alloc] initWithRootViewController:childVc];
        }
        [self addChildViewController:nav];
    }
}

@end
